package com.powernode.mybatis.test;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * 正规的MyBatis代码
 * @author zcj
 * @version 1.0
 * @since 1.0
 */
public class MyBatisComplete {
    public static void main(String[] args) {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
            //开启会话(开启事务)
            sqlSession = sqlSessionFactory.openSession();//注意不能加true
            //执行sql语句，处理相关业务
            int count = sqlSession.insert("insertCar");
            System.out.println("成功插入" + count + "条记录");
            //代码执行到这，表示没有发生任何异常，提交事务，终止事务
            sqlSession.commit();
        } catch (IOException e) {
            //出现异常回滚事务
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            e.printStackTrace();
        } finally {
            //关闭事务(释放资源)
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}
